package com.equinox.spring_sse;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

/**
 * 测试sse
 *  
 *  
 *  
 * @author Thinker
 *
 */
@CrossOrigin
@RestController
@RequestMapping("/sse")
public class TestController {
	
	
	/**
	 * 用于创建连接
	 */
	@GetMapping("/connect/{userId}")
	public SseEmitter connect(@PathVariable String userId) {
		return SseEmitterServer.connect(userId);
	}

	/**
	 * 推送给所有人
	 *
	 * @param message
	 * @return
	 */
	/*
	 * @GetMapping("/push/{message}") public ResponseEntity<String>
	 * push(@PathVariable(name = "message") String message) {
	 * SseEmitterServer.batchSendMessage(message); return
	 * ResponseEntity.ok("WebSocket 推送消息给所有人"); }
	 */
	@GetMapping("/push")
	@Scheduled(cron = "0/10 * * * * ?")
	public ResponseEntity<String> push() {
		Random r = new Random();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date time = new Date();
		String strTime = format.format(time);
		SseEmitterServer.batchSendMessage(String.format("测试sse服务器推送,推送时间为:%s", strTime));
		return ResponseEntity.ok("WebSocket 推送消息给所有人");
	}

	/**
	 * 发送给单个人
	 *
	 * @param message
	 * @param userid
	 * @return
	 */
	@GetMapping("/push_one/{messsage}/{userid}")
	public ResponseEntity<String> pushOne(@PathVariable(name = "message") String message,
			@PathVariable(name = "userid") String userid) {
		SseEmitterServer.sendMessage(userid, message);
		return ResponseEntity.ok("WebSocket 推送消息给" + userid);
	}

	/**
	 * 关闭连接
	 */
	@GetMapping("/close/{userid}")
	public ResponseEntity<String> close(@PathVariable("userid") String userid) {
		SseEmitterServer.removeUser(userid);
		return ResponseEntity.ok("连接关闭");
	}

}
